package net.xilou.weibo;

import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapListHandler;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * Created by yong on 2016/3/23.
 */
public class DBHelper {
    protected static Connection conn = null;
    static {
        try {
            String driver = ConfigerHelper.get("jdbc.driver");
            String url = ConfigerHelper.get("jdbc.url");
            String userName = ConfigerHelper.get("jdbc.username");
            String password = ConfigerHelper.get("jdbc.password", "");

            DbUtils.loadDriver(driver);
            conn = DriverManager.getConnection(url, userName, password);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
//            DbUtils.closeQuietly(conn);
        }
    }

    public static QueryRunner createQuery() {
        return new QueryRunner();
    }

    public static Connection getConnection() {
        return conn;
    }

    public static int execute(String sql, Object... params) throws SQLException{
        QueryRunner query = new QueryRunner();
        return query.update(conn, sql, params);
    }

    public static List query(String sql, Object... params) throws SQLException{
        QueryRunner qr = new QueryRunner();
        qr.update(conn, "SET names utf8mb4");
        return (List)qr.query(conn, sql, new MapListHandler(), params);
    }

    public static Map<String, Object> findOne(String sql, Object... params) throws SQLException{
        QueryRunner qr = new QueryRunner();
        List result = (List)qr.query(conn, sql, new MapListHandler(), params);
        if(result.size() > 0) {
            return (Map) result.get(0);
        } else {
            return null;
        }
    }

    public static int count(String sql, Object... params) throws SQLException {
        QueryRunner qr = new QueryRunner();
        List result = (List)qr.query(conn, sql, new MapListHandler(), params);
        if(result.size() > 0) {
            Map row = (Map) result.get(0);
            Number c = (Number)row.get("c");
            return c.intValue();
        } else {
            return 0;
        }
    }
}
